package com.example.questionsystem.modules.qu.controller;

import com.example.questionsystem.core.api.ApiRest;
import com.example.questionsystem.core.api.controller.BaseController;
import com.example.questionsystem.modules.qu.Vo.PackageVo;
import com.example.questionsystem.modules.qu.Vo.ProAndSubAndQu;
import com.example.questionsystem.modules.qu.Vo.SubjectQuestionVo;
import com.example.questionsystem.modules.qu.entity.*;
import com.example.questionsystem.modules.qu.service.PackageService;
import com.example.questionsystem.modules.qu.service.ProjectsService;
import com.example.questionsystem.modules.qu.service.QuestionBankService;
import com.example.questionsystem.modules.qu.service.SubjectsService;
import com.example.questionsystem.modules.qu.service.impl.TotalScoreMismatchException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = {"打包API"})
@RestController
@RequestMapping("/packaged")
public class PackagedController extends BaseController {

    @Resource
    private ProjectsService projectsService;

    @Resource
    private SubjectsService subjectsService;

    @Resource
    private QuestionBankService questionBanksService;

    @Resource
    private PackageService packageService;

    /**
     * 旧版就考试打包 - 试考
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping("/generateOldPackage")
    public void generateExamOldPackage(@Valid @RequestBody PackageRequest request,
                                       HttpServletResponse response) throws Exception {
        try {
            packageService.generateExamOldPackage(request, response);
        } catch (IOException e) {
            // 处理 IOException 异常
            response.reset();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("打包过程中发生 IO 错误: " + e.getMessage());
        } catch (TotalScoreMismatchException e) {
            // 处理 TotalScoreMismatchException 异常
            response.reset();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("题型总分与设置总分不一致: " + e.getMessage());
        }
    }
    /**
     * 正考
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping("/generateOldFormalPackage")
    public void generateExamOldFormalPackage(@Valid @RequestBody PackageRequest request,
                                       HttpServletResponse response) throws Exception {
        try {
            packageService.generateExamOldFormalPackage(request, response);
        } catch (IOException e) {
            // 处理 IOException 异常
            response.reset();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("打包过程中发生 IO 错误: " + e.getMessage());
        } catch (TotalScoreMismatchException e) {
            // 处理 TotalScoreMismatchException 异常
            response.reset();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("题型总分与设置总分不一致: " + e.getMessage());
        }
    }
    @ResponseBody
    @PostMapping("/generateSession")
    public ApiRest generateSessionExamPackage(@RequestBody PackageVo requestData) throws IOException {
       try {
           packageService.generateSession(requestData);
          return success("打包成功");
       } catch (Exception e) {
          return failure(e.getMessage());
       }
    }
    /**
     * 项目打包
     * @param projectId
     * @return
     */
    @GetMapping("/ProjectPackagedSettings")
    public ApiRest<ProAndSubAndQu> getPackaged(String  projectId) {
        ProAndSubAndQu proAndSubAndQu = new ProAndSubAndQu();
        Projects projects = projectsService.getById(projectId);
        proAndSubAndQu.setProjects(projects);
        List<SubjectSessions> subjects = subjectsService.getSubjectSessionsByProjectId(projectId);
        List<SubjectQuestionVo> subjectQuestionVos = new ArrayList<>();
        for (SubjectSessions subject : subjects) {
            SubjectQuestionVo subjectQuestionVo = new SubjectQuestionVo();
            List<QuestionBanks> questionBanks = questionBanksService.getQuestionBanksBySubjectId(subject.getSubjectId());
           subjectQuestionVo.setQuestionBanksList(questionBanks);
            subjectQuestionVo.setSubjectSessions(subject);
            subjectQuestionVos.add(subjectQuestionVo);
        }
        proAndSubAndQu.setSubjectQuestionVos(subjectQuestionVos);
        return success("获取成功", proAndSubAndQu);
    }

    /**
     * 按场次打包
     * @param projectId
     * @param sessionName
     * @return
     */
    @GetMapping("/SessionPackagedSettings")
    public ApiRest<ProAndSubAndQu> getPackagedBySession(String  projectId, String sessionName) {
        ProAndSubAndQu proAndSubAndQu = new ProAndSubAndQu();
        Projects projects = projectsService.getById(projectId);
        proAndSubAndQu.setProjects(projects);
        List<SubjectSessions> subjectBySessionName = subjectsService.getSubjectBySessionName(projectId, sessionName);
        List<SubjectQuestionVo> subjectQuestionVos = new ArrayList<>();
        for (SubjectSessions subject : subjectBySessionName) {
            SubjectQuestionVo subjectQuestionVo = new SubjectQuestionVo();
            List<QuestionBanks> questionBanks = questionBanksService.getQuestionBanksBySubjectId(subject.getSubjectId());
            subjectQuestionVo.setQuestionBanksList(questionBanks);
            subjectQuestionVo.setSubjectSessions(subject);
            subjectQuestionVos.add(subjectQuestionVo);
        }
        proAndSubAndQu.setSubjectQuestionVos(subjectQuestionVos);
        return success("获取成功", proAndSubAndQu);
    }
    /**
     * 按科目打包
     * @param projectId
     * @param subjectId
     * @return
     */
    @GetMapping("/SubjectPackagedSettings")
    public ApiRest<ProAndSubAndQu> getPackagedBySubject(String  projectId, String subjectId) {
        ProAndSubAndQu proAndSubAndQu = new ProAndSubAndQu();
        Projects projects = projectsService.getById(projectId);
        proAndSubAndQu.setProjects(projects);
        List<SubjectSessions> subjectBySessionName = subjectsService.getSubjects(projectId, subjectId);
        List<SubjectQuestionVo> subjectQuestionVos = new ArrayList<>();
        for (SubjectSessions subject : subjectBySessionName) {
            SubjectQuestionVo subjectQuestionVo = new SubjectQuestionVo();
            List<QuestionBanks> questionBanks = questionBanksService.getQuestionBanksBySubjectId(subject.getSubjectId());
            subjectQuestionVo.setQuestionBanksList(questionBanks);
            subjectQuestionVo.setSubjectSessions(subject);
            subjectQuestionVos.add(subjectQuestionVo);
        }
        proAndSubAndQu.setSubjectQuestionVos(subjectQuestionVos);
        return success("获取成功", proAndSubAndQu);
    }
    /**
     * 获取知识点题型统计
     * @param projectId 项目ID
     * @param subjectId 科目ID
     * @return 知识点题型数量统计
     */
    @GetMapping("/knowledgeStats")
    public ApiRest<Map<String, Map<String, Integer>>> getKnowledgeQuestionStats(
            @RequestParam String projectId,
            @RequestParam String subjectId) {
        Map<String, Map<String, Integer>> stats = questionBanksService.getKnowledgeQuestionStats(subjectId);
        return success("统计成功", stats);
    }
    @PostMapping("/generateUseCountPackage")
    public ApiRest generateUseCountPackage(@RequestBody ExtractionConfigDto requestData, HttpServletResponse response) {
        try {
            packageService.generateUseCountPackage(requestData, response);
            return success("打包成功,请检查C:/kz目录");
        } catch (Exception e) {
            return failure(e.getMessage());
        }
    }

    @PostMapping("/generateSessionEncrypted")
    public void generateSessionEncryptedExamPackage(@RequestBody PackageVo requestData,
                                    HttpServletResponse response) throws IOException {
        try {
            packageService.generateSessionEncrypted(requestData, response);
        } catch (IOException e) {
            response.reset();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("打包失败: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
